package com.sunshine.wrongquestionset.activity.login

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider

import com.google.android.material.snackbar.Snackbar

import com.sunshine.wrongquestionset.R
import com.sunshine.wrongquestionset.room.entity.AppConfigEntity
import com.sunshine.wrongquestionset.room.entity.UserEntity
import es.dmoral.toasty.Toasty

import kotlinx.android.synthetic.main.fragment_register.*

class RegisterFragment : Fragment() {

    private lateinit var viewModel: LoginViewModel

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_register, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        viewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(requireActivity().application)).get(LoginViewModel::class.java)

        to_register.setOnClickListener {
            val userId = edit_user_id.text?.toString()
            val password = edit_password.text?.toString()
            val passwordAgain = edit_password_again.text?.toString()

            if (userId.isNullOrBlank() || userId.length > 20) {
                Snackbar.make(to_register, getString(R.string.user_id_error), Snackbar.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            if (password.isNullOrBlank() || password.length > 40) {
                Snackbar.make(to_register, getString(R.string.password_error), Snackbar.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            if (passwordAgain.isNullOrBlank() || password != passwordAgain) {
                Snackbar.make(to_register, getString(R.string.password_and_password_again_error), Snackbar.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            //该账号已经注册过
            if (viewModel.findUser(userId)) {
                Snackbar.make(to_register, getString(R.string.user_id_already_register), Snackbar.LENGTH_SHORT).show()
            }
            //去注册
            else {
                val userEntity = UserEntity(userId, password)
                viewModel.toRegister(userEntity)
                Toasty.success(requireContext(), getString(R.string.register_success), Toasty.LENGTH_SHORT).show()
                requireActivity().supportFragmentManager.popBackStack()
            }
        }
    }
}